<template>
  <div>
    <Header :title="'返回'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card>
      <a-spin :spinning="spinning" size="large">
        <div class="form-contanier">
          <template v-if="type == 0">
            <h2>每日签到任务</h2>
            <a-form-model ref="formSign" :model="formSign" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rulesSign">
              <div class="section-title">
                <h3>基础信息</h3>
              </div>
              <template v-if="id == 'add'">
                <a-form-model-item label="支持的小程序" prop="weIds">
                  <a-select v-model="formSign.weIds" mode="multiple" style="width: 80%" showArrow @change="handleChange">
                    <a-select-option :value="item.weid" v-for="item in env === 'production' ? brandListPro : brandList" :key="item.weid">{{ item.brandName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </template>
              <a-form-model-item label="支持的小程序" prop="weIds" v-else>{{ formSign.weId | brandName(env === 'production' ? brandListPro : brandList) }}</a-form-model-item>
              <div class="section-title">
                <h3>露出信息</h3>
                <span>以下信息为对用户侧展示的信息，请认真填写</span>
              </div>
              <a-form-model-item label="icon图" prop="imgList">
                <JImageUpload :uploadParams="getUploadParams()" :fileSize="0.5" :accept="'image/*'" :isMultiple="false" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
                <div class="upload__tip" style="line-height: 16px">图片比例1:1，支持jpg/png/gif格式，文件大小不超过500k</div>
              </a-form-model-item>
              <a-form-model-item label="任务名称" prop="taskName"> <a-input v-model="formSign.taskName" allowClear :maxLength="20" /> </a-form-model-item>
              <a-form-model-item label="任务说明" prop="taskDescription"> <a-input v-model="formSign.taskDescription" allowClear :maxLength="25" /> </a-form-model-item>
              <a-form-model-item label="按钮文案" prop="buttonName"> <a-input v-model="formSign.buttonName" allowClear :maxLength="8" placeholder="任务完成前按钮上展示的文案" /> </a-form-model-item>
              <a-form-model-item label="排序值" prop="sort"> <a-input-number :min="1" :max="100" v-model="formSign.sort" allowClear /> </a-form-model-item>
              <a-form-model-item label="跳转链接" prop="taskLink"> <a-input v-model="formSign.taskLink" allowClear /> </a-form-model-item>
              <template v-if="id != 'add'">
                <!-- <a-form-model-item label="任务状态" prop="status">
                  <a-radio-group name="radioGroup" v-model="formSign.status">
                    <a-radio :value="1">下架</a-radio>
                    <a-radio :value="0">上架</a-radio>
                  </a-radio-group>
                </a-form-model-item> -->
              </template>
              <a-form-model-item :wrapper-col="{ span: 24 }">
                <div style="text-align: center" v-if="formSign.status != 0">
                  <a-button type="primary" @click="onSubmit" :loading="saveLoading" v-if="formSign.status != 2">保存</a-button>
                  <template v-if="id != 'add' && formSign.status != 2">
                    <a-button style="margin-left: 10px" @click="onSubmit('goLive')" v-if="formSign.status == 1">上架</a-button>
                    <a-button style="margin-left: 10px" @click="onSubmit('forbidden')" v-if="formSign.status == 0">下架</a-button>
                  </template>
                  <a-button style="margin-left: 10px" @click="headerBack">取消</a-button>
                </div>
              </a-form-model-item>
            </a-form-model>
          </template>
          <template v-else>
            <h2>{{ type | typeName(typeArr) }}</h2>
            <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
              <div class="section-title">
                <h3>基础信息</h3>
              </div>
              <a-form-model-item label="任务别名" prop="taskAliasName"> <a-input v-model="form.taskAliasName" allowClear :maxLength="20" style="width: 80%" /> </a-form-model-item>
              <template v-if="id == 'add'">
                <a-form-model-item label="支持的小程序" prop="weIds">
                  <a-select v-model="form.weIds" mode="multiple" style="width: 80%" showArrow @change="handleChange">
                    <a-select-option :value="item.weid" v-for="item in env === 'production' ? brandListPro : brandList" :key="item.weid">{{ item.brandName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </template>
              <a-form-model-item label="支持的小程序" required v-else>{{ form.weId | brandName(env === 'production' ? brandListPro : brandList) }}</a-form-model-item>
              <a-form-model-item label="参活人群" required style="margin-bottom: 12px">
                <a-radio-group name="radioGroup" v-model="form.isDesignatedPopulation">
                  <a-radio :value="0">全部人群</a-radio>
                  <a-radio :value="1">指定人群</a-radio>
                </a-radio-group>
              </a-form-model-item>

              <div v-if="form.isDesignatedPopulation == 1">
                <a-form-model-item :wrapper-col="{ span: 18, offset: 5 }">
                  <a-checkbox :checked="cardLevelsCheck" @change="e => onCheckChange(e, 'cardLevels')" style="color: rgba(0, 0, 0, 0.85)">会员品牌卡等级</a-checkbox><br />
                  <a-checkbox-group v-model="form.cardLevels" @change="cardLevelsChange">
                    <a-checkbox :value="item.id" v-for="(item, index) in rankOptions" :key="index">{{ item.name }}</a-checkbox>
                  </a-checkbox-group>
                </a-form-model-item>
                <a-form-model-item :wrapper-col="{ span: 18, offset: 5 }">
                  <div class="table-check">
                    <a-checkbox :checked="peopleCheck" @change="e => onCheckChange(e, 'people')" style="color: rgba(0, 0, 0, 0.85)">目标人群(可多选)</a-checkbox>
                    <a-button icon="plus" type="link" @click="handlePeople">添加</a-button>
                  </div>
                  <a-table :dataSource="targetPerson" :columns="targetColums" :pagination="false" :rowKey="(r, index) => index">
                    <span slot="action" slot-scope="text, record, index">
                      <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(index, 'person')">
                        <a><a-icon type="delete" /></a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                </a-form-model-item>
                <a-form-model-item :wrapper-col="{ span: 18, offset: 5 }">
                  <div class="table-check">
                    <a-checkbox :checked="shopCheck" @change="e => onCheckChange(e, 'shop')" style="color: rgba(0, 0, 0, 0.85)">门店包(只允许选择一个)</a-checkbox>
                    <a-button type="link" icon="plus" @click="handleShop">添加</a-button>
                  </div>
                  <a-table :dataSource="shopList" :columns="shopColums" :pagination="false" :rowKey="(r, index) => index">
                    <span slot="action" slot-scope="text, record, index">
                      <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(index, 'shop')">
                        <a><a-icon type="delete" /></a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                  <div class="tip" style="margin-top: 24px" v-show="tipReward">{{ tipText }}</div>
                </a-form-model-item>
              </div>
              <a-form-model-item label="有效期" prop="timePicker">
                <a-range-picker
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="form.timePicker"
                  style="width: 80%"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-model-item>
              <a-form-model-item label="执行方式" prop="executionMode">
                <a-select v-model="form.executionMode" style="width: 80%">
                  <a-select-option :value="0">周期内定期循环</a-select-option>
                  <a-select-option :value="1">周期内始终有效</a-select-option>
                </a-select>
              </a-form-model-item>
              <template v-if="form.executionMode == 0">
                <a-form-model-item label="执行周期" prop="executionCycle">
                  <a-select v-model="form.executionCycle" style="width: 80%">
                    <a-select-option :value="0">每天执行</a-select-option>
                    <a-select-option :value="1">每周执行</a-select-option>
                    <a-select-option :value="2">每月执行</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="每周执行" v-if="form.executionCycle == 1" prop="week" required>
                  <a-select v-model="form.week" mode="multiple" style="width: 80%" allowClear showArrow>
                    <a-select-option :value="index + 1" v-for="(item, index) in weekList" :key="index">{{ item }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="每月执行" v-if="form.executionCycle == 2" prop="day" required>
                  <a-select v-model="form.day" mode="multiple" style="width: 80%" allowClear showArrow>
                    <a-select-option :value="item" v-for="item in dayList" :key="item">{{ item }}</a-select-option>
                  </a-select>
                  <div>请注意2月没有29、30日，个别月份没有31日</div>
                </a-form-model-item>
                <a-form-model-item label="生效时间" prop="time">
                  <RankTimePicker ref="rankTimePicker" :setTimeStart.sync="form.executionStartTime" :setTimeEnd.sync="form.executionEndTime"> </RankTimePicker>
                  <div class="tip" v-show="tipReward2">{{ tipText2 }}</div>
                </a-form-model-item>
              </template>
              <!-- <template v-if="id != 'add'">
                <a-form-model-item label="任务状态" prop="status">
                  <a-radio-group name="radioGroup" v-model="form.status">
                    <a-radio :value="1">下架</a-radio>
                    <a-radio :value="0">上架</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </template> -->

              <a-divider dashed></a-divider>
              <div class="section-title">
                <h3>露出信息</h3>
                <span>以下信息为对用户侧展示的信息，请认真填写</span>
              </div>
              <a-form-model-item label="icon图" prop="imgList">
                <JImageUpload :uploadParams="getUploadParams()" :fileSize="0.5" :accept="'image/*'" :isMultiple="false" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
                <div class="upload__tip" style="line-height: 16px">图片比例1:1，支持jpg/png/gif格式，文件大小不超过500k</div>
              </a-form-model-item>
              <a-form-model-item label="任务名称" prop="taskName"> <a-input v-model="form.taskName" allowClear :maxLength="20" /> </a-form-model-item>
              <a-form-model-item label="任务说明" prop="taskDescription"> <a-input v-model="form.taskDescription" allowClear :maxLength="25" /> </a-form-model-item>
              <a-form-model-item label="按钮文案" prop="buttonName"> <a-input v-model="form.buttonName" allowClear :maxLength="8" placeholder="任务完成前按钮上展示的文案" /> </a-form-model-item>
              <a-form-model-item label="排序值" prop="sort"> <a-input-number :min="1" :max="100" v-model="form.sort" allowClear /> </a-form-model-item>
              <a-form-model-item label="跳转链接" prop="taskLink"> <a-input v-model="form.taskLink" allowClear /> </a-form-model-item>
              <template v-if="type != 3">
                <a-divider dashed></a-divider>
                <div class="section-title">
                  <h3>奖励信息</h3>
                </div>
                <a-form-model-item label="奖励门槛" prop="requiredTimes">
                  <span>任务完成次数：</span> <a-input-number :min="1" v-model="form.requiredTimes" allowClear />
                  <span style="margin-left: 8px">(用户在有效期内完成指定任务次数后才能领取任务奖励)</span>
                </a-form-model-item>

                <a-form-model-item label="奖励内容" prop="gainPoints"><span>积分：</span> <a-input-number :min="0" v-model="form.gainPoints" allowClear /> </a-form-model-item>
              </template>
              <a-form-model-item :wrapper-col="{ span: 24 }">
                <div style="text-align: center" v-if="form.status != 0">
                  <a-button type="primary" @click="onSubmit" :loading="saveLoading" v-if="form.status != 2">保存</a-button>
                  <template v-if="id != 'add' && form.status != 2">
                    <a-button style="margin-left: 10px" @click="onSubmit('goLive')" v-if="form.status == 1">上架</a-button>
                    <a-button style="margin-left: 10px" @click="onSubmit('forbidden')" v-if="form.status == 0">下架</a-button>
                  </template>
                  <a-button style="margin-left: 10px" @click="headerBack">取消</a-button>
                </div>
              </a-form-model-item>
            </a-form-model>
          </template>
        </div>
      </a-spin>
    </a-card>
    <a-modal :visible="visible" title="提示" @cancel="visible = false" @ok="handleHistory" okText="修改历史任务" cancelText="取消">
      <h3>存在同类型进行中的任务，无法上架</h3>

      <div v-for="(item, index) in clashTime" :key="item.id" style="margin-top: 12px">
        任务{{ index + 1 }}：【{{ item.brand | brandName(env === 'production' ? brandListPro : brandList) }}】{{ item.title }}<br />
        {{ item.startTime }} - {{ item.endTime }}
      </div>
    </a-modal>
    <a-modal :visible="visible2" title="提示" @cancel="visible2 = false">
      <h3>当前任务有效期和历史任务重叠</h3>
      <div v-if="this.form.timePicker && this.form.timePicker.length">当前任务时间：{{ this.form.timePicker[0] }}~{{ this.form.timePicker[1] }}</div>
      <div v-for="(item, index) in clashTime" :key="item.id" style="margin-top: 12px">
        <p>任务{{ index + 1 }}：【{{ item.brand | brandName(env === 'production' ? brandListPro : brandList) }}】{{ item.title }}</p>
        <a-range-picker
          :show-time="{
            hideDisabledOptions: true,
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
          }"
          :placeholder="['开始时间', '结束时间']"
          v-model="item.timePicker"
          style="width: 80%"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </div>
      <template slot="footer">
        <a-button key="back" @click="openHistory"> 查看历史任务 </a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="editHistory"> 修改并保存 </a-button>
      </template>
    </a-modal>
    <a-modal :visible="visibleSign" title="提示" @cancel="visibleSign = false" @ok="visibleSign = false">
      <h3>存在同类型进行中的任务，无法上架</h3>

      <div v-for="(item, index) in clashTime" :key="item.id" style="margin-top: 12px">
        任务{{ index + 1 }}：【{{ item.brand | brandName(env === 'production' ? brandListPro : brandList) }}】{{ item.title }}
      </div>
    </a-modal>
    <PeoplePagModal ref="peoplePagModal" :logVisible.sync="logVisible" :channel="'member'" @updatePeople="updatePeople"> </PeoplePagModal>
    <ShopPagModal ref="shopPagModal" :logVisible.sync="logVisibleShop" @updateStore="updateStore"></ShopPagModal>
  </div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import { taskMixin } from './mixin'
import { taskDetail, addTask, updateTaskDetail, batchUpdateTask } from '@/api/marketingCenter/memberTask'
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload'
import RankTimePicker from '@/views/box/components/rankTimePicker'
import PeoplePagModal from '@/views/marketingCenter/components/peoplePagModal'
import ShopPagModal from '@/views/marketingCenter/components/shopPagModal'

let targetColums = [
  { title: '人群包ID', dataIndex: 'id' },
  { title: '人群包名称', dataIndex: 'name' },
  { title: '操作', scopedSlots: { customRender: 'action' } }
]
let shopColums = [
  { title: '门店包ID', dataIndex: 'id' },
  { title: '门店包名称', dataIndex: 'name' },
  { title: '操作', scopedSlots: { customRender: 'action' } }
]
let weekList = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
let dayList = []
for (let i = 1; i <= 31; i++) {
  dayList.push(i)
}
let rankOptions = [
  { id: '1', name: '银卡' },
  { id: '2', name: '金卡' },
  { id: '3', name: '铂金卡/白金卡' }
]

export default {
  mixins: [taskMixin],
  components: { JImageUpload, RankTimePicker, PeoplePagModal, ShopPagModal },
  data() {
    return {
      id: null,
      type: null,
      spinning: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      formSign: {
        weIds: [],
        taskName: null,
        taskDescription: '',
        buttonName: '',
        taskLink: '/packages/wm-cloud-jnbyintegral/integralTask/index',
        sort: null,
        icon: ''
      },
      rulesSign: {
        weIds: [{ required: true, message: '请选择小程序', trigger: ['change', 'blur'] }],
        taskName: [{ required: true, message: '请输入任务名称，最多20个字', trigger: 'blur', max: 20 }],
        taskDescription: [{ required: true, message: '请输入任务说明，最多25个字', trigger: 'blur', max: 25 }],
        buttonName: [{ required: true, message: '请输入按钮文案，最多8个字', trigger: 'blur', max: 8 }],
        taskLink: [{ required: true, trigger: 'blur', message: '请输入跳转链接' }],
        sort: [{ required: true, message: '请输入排序值，且为数字', trigger: 'blur', pattern: /^[1-9]\d*$/ }],
        imgList: [{ required: true, message: '请上传icon图', trigger: ['blur', 'change'], validator: this.validatorImg, type: 'array' }]
        // status: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }]
      },
      imgList: [],
      form: {
        taskAliasName: '',
        weIds: [],
        isDesignatedPopulation: 0,
        cardLevels: [],
        timePicker: undefined,
        taskName: '',
        taskDescription: '',
        buttonName: '',
        taskLink: '',
        sort: null,
        icon: '',
        executionMode: null,
        executionStartTime: null,
        executionEndTime: null
      },
      rules: {
        taskAliasName: [{ required: true, message: '请输入活动名称，最多20个字', trigger: 'blur', max: 20 }],
        weIds: [{ required: true, message: '请选择小程序', trigger: ['change', 'blur'] }],
        timePicker: [{ required: true, message: '请选择活动时间', trigger: ['change', 'blur'] }],
        executionMode: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }],
        imgList: [{ required: true, message: '请上传icon图', trigger: ['blur', 'change'], validator: this.validatorImg, type: 'array' }],
        taskName: [{ required: true, message: '请输入任务名称，最多20个字', trigger: 'blur', max: 20 }],
        taskDescription: [{ required: true, message: '请输入任务说明，最多25个字', trigger: 'blur', max: 25 }],
        buttonName: [{ required: true, message: '请输入按钮文案，最多8个字', trigger: 'blur', max: 8 }],
        taskLink: [{ required: true, trigger: 'blur', message: '请输入跳转链接' }],
        sort: [{ required: true, message: '请输入排序值，且为数字', trigger: 'blur', pattern: /^[1-9]\d*$/ }],
        executionCycle: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }],
        week: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }],
        day: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }],
        time: [{ required: true, message: '请选择', trigger: ['change', 'blur'], validator: this.validatorTime }],
        // status: [{ required: true, message: '请选择', trigger: ['change', 'blur'] }],
        requiredTimes: [{ required: true, trigger: ['change', 'blur'], validator: this.validatorRequiredTimes }],
        gainPoints: [{ required: true, trigger: ['change', 'blur'], validator: this.validatorGainPoints }]
      },
      cardLevelsCheck: false,
      peopleCheck: false,
      shopCheck: false,
      targetPerson: [],
      targetColums,
      shopList: [],
      shopColums,
      tipText: '',
      tipReward: false,
      tipText2: '',
      tipReward2: false,
      dayList,
      weekList,
      rankOptions,
      saveLoading: false,
      visible: false,
      visible2: false,
      logVisible: false,
      logVisibleShop: false,
      clashTime: [],
      loading: false,
      visibleSign: false,
      env: process.env.NODE_ENV
    }
  },
  created() {
    this.initialPage()
  },
  mounted() {},
  methods: {
    moment,
    async initialPage() {
      this.spinning = true
      this.id = this.$route.params.id
      let type = this.$route.params.type
      let result = this.typeArr.filter(e => e.enText == type)[0]

      if (this.id == 'add') {
        this.type = result.code
        if (this.type == 0) {
          // 签到
          this.imgList = ['https://img.bzhz.jnbygroup.com/memberTask_img_sign.png']
        }
        if (this.type == 1) {
          // 订单评价
          this.imgList = ['https://img.bzhz.jnbygroup.com/memberTask_img_comment.png']
          this.$set(this.form, 'requiredTimes', 1)
          this.$set(this.form, 'gainPoints', null)
          this.form.taskLink = '/ec_orderDetail/orderlist'
        }
        if (this.type == 2) {
          // 社区发帖
          this.imgList = ['https://img.bzhz.jnbygroup.com/memberTask_img_post.png']
          this.$set(this.form, 'requiredTimes', 1)
          this.$set(this.form, 'gainPoints', null)
          this.form.taskLink = '/packages/wm-cloud-jnbycommunity/publish/index'
        }
      } else {
        await this.fetchData(this.id)
        if (type == 'copy') {
          this.id = 'add'
          delete this.formSign.status
          delete this.form.status
        }
      }
      this.$forceUpdate()
      this.spinning = false
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleSelectChange() {},
    fetchData(id) {
      let params = {
        requestData: {
          id: id
        }
      }
      return taskDetail(params).then(res => {
        if (res.code == 0) {
          const { data } = res
          this.type = data.taskType
          this.imgList = [data.icon]
          if (data.taskType == 0) {
            this.formSign = data
            this.$set(this.formSign, 'weIds', [data.weId])
          } else {
            this.form = data
            this.$set(this.form, 'weIds', [data.weId])
            this.$set(this.form, 'timePicker', [data.startTime, data.endTime])
            if (this.form.executionCycleAttr) {
              if (this.form.executionCycle == 1) {
                this.$set(
                  this.form,
                  'week',
                  this.form.executionCycleAttr.split(',').map(e => parseInt(e))
                )
              } else if (this.form.executionCycle == 2) {
                this.$set(
                  this.form,
                  'day',
                  this.form.executionCycleAttr.split(',').map(e => parseInt(e))
                )
              }
            }

            if (data.cardLevels && data.cardLevels.length > 0) {
              this.form.cardLevels = data.cardLevels.map(e => e.id)
              this.cardLevelsCheck = true
            } else {
              this.form.cardLevels = []
            }

            this.targetPerson = data.peoplePag ? data.peoplePag : []
            if (data.peoplePag && data.peoplePag.length) this.peopleCheck = true
            this.shopList = data.storePag ? [data.storePag] : []
            if (this.shopList.length) this.shopCheck = true
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleChange(value) {
      // console.log(value)
      if (this.type == 0) {
        this.formSign.weIds = value
      } else {
        this.form.weIds = value
      }
    },
    fileImageChange(list) {
      if (this.type == 0) {
        this.formSign.imgList = list
        this.formSign.icon = list.length > 0 ? list[0].url : ''
      } else {
        this.form.imgList = list
        this.form.icon = list.length > 0 ? list[0].url : ''
      }
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    validatorImg(rule, value, callback) {
      if (this.form.imgList || this.formSign.imgList) {
        callback()
      } else {
        callback('请上传图标')
      }
    },
    validatorTime(rule, value, callback) {
      let sTime = this.form.executionStartTime
      let eTime = this.form.executionEndTime
      if (sTime && eTime) {
        callback()
      } else {
        callback('请选择时间')
      }
    },
    validatorRequiredTimes(rule, value, callback) {
      let testValue = new RegExp(/(^-?[1-9]([0-9]*)$|^-?[0-9]$)/).test(value)
      if (value >= 1 && testValue) {
        callback()
      } else {
        callback('请输入大于等于1以上的整数')
      }
    },
    validatorGainPoints(rule, value, callback) {
      let testValue = new RegExp(/(^-?[1-9]([0-9]*)$|^-?[0-9]$)/).test(value)
      if (value >= 0 && testValue) {
        callback()
      } else {
        callback('请输入大于等于0以上的整数')
      }
    },
    onCheckChange(e, type) {
      switch (type) {
        case 'cardLevels':
          this.cardLevelsCheck = !this.cardLevelsCheck
          break
        case 'people':
          this.peopleCheck = !this.peopleCheck
          break
        case 'shop':
          this.shopCheck = !this.shopCheck
          break
      }
    },
    cardLevelsChange(checkedValue) {
      this.cardLevelsCheck = checkedValue.length != 0
    },
    handleDelete(index, type) {
      if (type == 'person') {
        this.targetPerson.splice(index, 1)
        this.peopleCheck = this.targetPerson.length != 0
      }
      if (type == 'shop') {
        this.shopList.splice(index, 1)
        this.shopCheck = this.shopList.length != 0
      }
    },
    handlePeople() {
      this.$refs.peoplePagModal.getLog('parent')
      this.logVisible = true
    },
    updatePeople(record) {
      let newRecord = {
        id: record.groupId,
        name: record.groupName,
        states: record.states
      }
      if (this.targetPerson.length == 0) {
        this.targetPerson.push(newRecord)
        this.$message.success('添加成功')
      } else {
        let obj = this.targetPerson.find(item => item.id == newRecord.id)
        if (!obj) {
          this.targetPerson.push(newRecord)
          this.$message.success('添加成功')
        } else {
          this.$message.warning('已存在，无需重复添加')
        }
      }
      if (this.targetPerson.length) this.peopleCheck = true
    },
    handleShop() {
      this.$refs.shopPagModal.getLog('parent')
      this.logVisibleShop = true
    },
    updateStore(record) {
      let newRecord = {
        id: record.storePackageId,
        name: record.storePackageName
      }
      this.shopList = [newRecord]
      this.$message.success('添加成功')
      if (this.shopList.length) this.shopCheck = true
    },
    onSubmit(operate) {
      // console.log(this.type, this.id)
      if (this.type == 0) {
        this.$refs.formSign.validate(valid => {
          // console.log(valid, this.formSign)
          if (valid) {
            this.saveLoading = true
            this.spinning = true
            let data = JSON.parse(JSON.stringify(this.formSign))
            delete data.imgList
            if (this.id == 'add') {
              delete data.id
              data.taskType = this.type
              this.createTask(data)
            } else {
              if (operate == 'goLive') {
                this.saveLoading = false
                this.handleGoLive(data)
              } else if (operate == 'forbidden') {
                this.saveLoading = false
                this.handleForbidden(data)
              } else {
                delete data.status
                this.editTask(data)
              }
            }
          }
        })
      } else {
        this.$refs.form.validate(valid => {
          // console.log(valid, this.form)
          if (this.form.isDesignatedPopulation == 1) {
            if (!this.cardLevelsCheck && !this.peopleCheck && !this.shopCheck) {
              this.tipText = '至少选择一种指定人群'
              this.tipReward = true
              return
            } else {
              if (this.cardLevelsCheck && this.form.cardLevels.length == 0) {
                this.tipText = '请选择卡等级'
                this.tipReward = true
                return
              }
              if (this.peopleCheck && this.targetPerson.length == 0) {
                this.tipText = '请选择人群包'
                this.tipReward = true
                return
              }
              if (this.shopCheck && this.shopList.length == 0) {
                this.tipText = '请选择门店包'
                this.tipReward = true
                return
              }
            }
          }
          this.tipText = ''
          this.tipReward = false

          if (this.form.executionMode == 0 && (!this.form.executionStartTime || !this.form.executionEndTime)) {
            this.tipText2 = '请选择时间'
            this.tipReward2 = true
            return
          }
          this.tipText2 = ''
          this.tipReward2 = false
          if (valid) {
            this.saveLoading = true
            this.spinning = true
            let data = JSON.parse(JSON.stringify(this.form))
            delete data.timePicker
            data.startTime = this.form.timePicker[0]
            data.endTime = this.form.timePicker[1]

            // 参活人群
            if (this.form.isDesignatedPopulation == 1) {
              if (this.cardLevelsCheck) {
                data.cardLevels = this.rankOptions.filter(e => this.form.cardLevels.includes(e.id))
              } else {
                data.cardLevels = []
              }
              if (this.peopleCheck && this.targetPerson.length) {
                data.peoplePag = this.targetPerson
              } else {
                data.peoplePag = []
              }
              if (this.shopCheck && this.shopList.length) {
                data.storePag = this.shopList[0]
              } else {
                data.storePag = null
              }
            } else {
              data.cardLevels = []
              data.peoplePag = []
              data.storePag = null
            }
            // 执行方式
            if (this.form.executionMode == 1) {
              data.executionCycleAttr = null
              data.executionEndTime = null
              data.executionStartTime = null
              data.executionCycle = null
            } else {
              if (this.form.executionCycle == 1) {
                data.executionCycleAttr = this.form.week.join(',')
              } else if (this.form.executionCycle == 2) {
                data.executionCycleAttr = this.form.day.join(',')
              } else {
                data.executionCycleAttr = null
              }
            }
            delete data.imgList

            if (this.id == 'add') {
              delete data.id
              delete data.weId
              delete data.status
              delete data.version
              data.taskType = this.type
              this.createTask(data)
            } else {
              if (operate == 'goLive') {
                this.saveLoading = false
                this.handleGoLive(data)
              } else if (operate == 'forbidden') {
                this.saveLoading = false
                this.handleForbidden(data)
              } else {
                delete data.status
                this.editTask(data)
              }
            }
          }
        })
      }
    },
    // 创建
    createTask(data) {
      let params = {
        requestData: data
      }
      addTask(params).then(res => {
        this.saveLoading = false
        this.spinning = false
        if (res.code == 0) {
          if (res.data.length) {
            if (this.type == 0) {
              this.visibleSign = true
              this.clashTime = res.data
            } else {
              this.visible = true
              this.clashTime = res.data.map(e => {
                return { ...e, timePicker: [e.startTime, e.endTime] }
              })
            }
          } else {
            this.$message.success('新建成功')
            this.headerBack()
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 编辑
    editTask(data) {
      let params = {
        requestData: data
      }
      updateTaskDetail(params).then(res => {
        this.saveLoading = false
        this.spinning = false
        if (res.code == 0) {
          if (res.data.length) {
            if (this.type == 0) {
              this.visibleSign = true
              this.clashTime = res.data
            } else {
              this.visible = true
              this.clashTime = res.data.map(e => {
                return { ...e, timePicker: [e.startTime, e.endTime] }
              })
            }
          } else {
            this.$message.success('保存成功')
            this.headerBack()
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 启用
    handleGoLive(data) {
      let self = this
      this.$confirm({
        title: '确认要上架吗？',
        content: h => <div style="color:red;">确认上架后将以当前时刻作为新的活动开始时间</div>,
        okText: '确认上架',
        onOk() {
          data.status = 0
          self.editTask(data)
        },
        onCancel() {
          self.spinning = false
        }
      })
    },
    // 禁用
    handleForbidden(data) {
      let self = this
      this.$confirm({
        title: '确认要下架吗？',
        content: h => <div style="color:red;">确认下架后将以当前时刻作为新的活动结束时间</div>,
        okText: '确认下架',
        onOk() {
          data.status = 1
          self.editTask(data)
        },
        onCancel() {
          self.spinning = false
        }
      })
    },
    destroyAll() {
      this.$destroyAll()
    },
    // 时间重叠提示
    handleHistory() {
      this.visible = false
      this.visible2 = true
    },
    openHistory() {
      let arr = this.clashTime.map(e => e.id)
      let href = process.env.NODE_ENV === 'test' ? window.location.protocol + '//' + window.location.host + '/jnby-boot-admin' : window.location.protocol + '//' + window.location.host
      for (let id of arr) {
        window.open(`${href}/marketingCenter/memberPromotions/memberTask/edit/${id}`, '_blank')
      }
    },
    editHistory() {
      let fillingTime = this.clashTime.filter(e => e.timePicker && e.timePicker.length > 0)
      if (fillingTime.length != this.clashTime.length) {
        this.$message.warning('还有任务未填入时间')
        return
      }
      this.loading = true
      let params = {
        requestData: {
          updates: this.clashTime.map(e => {
            return {
              id: e.id,
              endTime: e.timePicker[1],
              startTime: e.timePicker[0]
            }
          })
        }
      }
      batchUpdateTask(params).then(res => {
        this.loading = false
        if (res.code == 0) {
          this.visible2 = false
          this.$message.success('修改历史任务时间成功')
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.form-contanier {
  max-width: 800px;
  width: 80%;
  margin: 0 auto;
}
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  h3 {
    margin-bottom: 0;
  }
  span {
    margin-left: 16px;
  }
}
.table-check {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tip {
  color: #f5222c;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: -1px;
}
</style>

